﻿using System;
using System.Globalization;
using System.Threading;
using System.Windows;
using System.Windows.Data;


namespace Coding4Fun.FakeCall.Controls
{
	public partial class InProgress : CallingUserControl
    {
		Timer _timer;
		
        public InProgress()
        {
			InitializeComponent();

			var isDarkTheme = ((Visibility)Application.Current.Resources["PhoneDarkThemeVisibility"]) == Visibility.Visible;
			expandOptions.DataContext = "/Coding4Fun.FakeCall;component/Media/icons/{0}/dropDown" + (isDarkTheme ? "Dark" : "Light") + ".png";
			expandOptions.IsChecked = Settings.ExpandTalkOptions;
			speakerButton.IsChecked = Settings.ExpandTalkOptions;
		}

		public new Visibility Visibility
		{
			get { return base.Visibility; }
			set
			{
				base.Visibility = value;

				if (value == Visibility.Visible)
				{
					_timer = new Timer(UpdateUi, null, 0, 1000);
				}
				else
				{
					DisposeTimers();
				}
			}
		}

		private void DisposeTimers()
		{
			if (_timer != null)
				_timer.Dispose();
		}

		public void UpdateUi(Object stateInfo)
		{
			Dispatcher.BeginInvoke(AddTime);
		}

		private void AddTime()
		{
			CurrentTicks++;
		}


		public int CurrentTicks
		{
			get { return (int)GetValue(CurrentTimeProperty); }
			set { SetValue(CurrentTimeProperty, value); }
		}

		// Using a DependencyProperty as the backing store for CurrentTime.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty CurrentTimeProperty =
			DependencyProperty.Register("CurrentTicks", typeof(int), typeof(InProgress), new PropertyMetadata(1));
		
		private void Button_Click(object sender, RoutedEventArgs e)
		{
			EndCall(e);
		}
	}

	public class TimeSpanConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			
			return (value == null) ? "XX:XX" : ReturnValue((int)value);
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}

		public static string ReturnValue(int value)
		{
			var time = TimeSpan.FromSeconds(value);
			return string.Format("{0:D2}:{1:D2}", time.Minutes, time.Seconds);
		}
	}
}
